package de.gwtprime.client.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.user.ACLManager;
import de.gwtprime.client.user.ACLManager.PrimeUIElement;
import de.gwtprime.shared.requestFactory.User2Proxy;

public class TooltipButton extends Button{
	
	boolean enabled = true;
	
	final DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
	
	String message = "";
	
	
	
	@Override
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}
	
	public void disableButtonWithMessage(boolean enabled, String message) {
		this.enabled = enabled;
		this.message = message;
	}
	
	
	public void enableFromUser(ClientFactory clientFactory, PrimeUIElement uiElement){
		enableFromUser(clientFactory, uiElement, null);
	}
	public void enableFromUser(ClientFactory clientFactory, PrimeUIElement uiElement, User2Proxy owner){
		
		if(clientFactory.getUser()==null){
			enabled = false;
			message = "Please log in first";
			return;
		}
		
		if(owner != null && owner.getEmail().equals(clientFactory.getUser().getEmail())){
			enabled = false;
			message = "You are the author and therefore can not vote";
			return;
		}
		
		boolean access = ACLManager.hasUserAccess(clientFactory.getUser(), uiElement);
		
		enabled = access;
		message = access ? "" : "You don't have enough trust";
	}
	
	public boolean checkEnabledStateAndShowMessage(ClickEvent event){
		
		if(!enabled){
			
			// If no message is set -> don't show popup
			if(message==null || message.equals("")){
				return false;
			}
			simplePopup.clear();
			simplePopup.add(new Label(message));
			Widget source = (Widget) event.getSource();
			int left = source.getAbsoluteLeft() + 10;
			int top = source.getAbsoluteTop() + 10;
			simplePopup.setPopupPosition(left, top);
			
			simplePopup.setAnimationEnabled(true);
			
			// Show the popup
			simplePopup.show();
			
			return false;
		}
		
		return true;
	}
	

}
